package com.hrbxlh.actionImpl;

import java.io.File;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hrbxlh.dao.*;
import com.hrbxlh.util.*;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


/**
 * -------------------------------------------------------
 * Copyright (c) 2017, 鑫联华信息科技股份有限公司
 * All rights reserved.
 * FileName：HomeworkTestActionImpl.java
 * Description：作业和试验HomeworkTestActionImpl类,负责操作作业数据以及实验数据。
 * History：
 * Date           Author               Desc
 * 2017.4.5		  xzx                 建立
 * -------------------------------------------------------
 */

@Component("homeworkTestActionImpl")
@Transactional
public class HomeworkTestActionImpl {

	@Resource(name="sourceDao")
	private SourceDao sourceDao;

	@Resource(name="homeworkTestDao")
	private HomeworkTestDao homeworkTestDao;

	@Resource(name = "relStuClassDao")
	private RelStuClassDao relStuClassDao;

	@Resource(name = "relationDao")
	private RelationDao relationDao;

	@Resource(name = "questionDao")
	private QuestionDao questionDao;

	@Autowired
	@Qualifier("courseActionImpl")
	private CourseActionImpl courseActionImpl;

	@Autowired
	@Qualifier("sourceActionImpl")
	private SourceActionImpl sourceActionImpl;

	@Resource(name = "teaStatisticsDao")
	private TeaStatisticsDao teaStatisticsDao;

	@Resource(name="courseDao")
	private CourseDao courseDao;

	@Resource(name="chapterDao")
	private ChapterDao chapterDao;

	org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(HomeworkTestActionImpl.class.getName());

	/**
	 * @description 查询某教师教的班级
	 * @param  paramMap Map<String,Object>
	 * @return List classId班级id,className班级名
	 * @throws Exception
	 */
	public List<Map<String,Object>> getTeaTeachClass(Map<String, Object> paramMap) throws Exception{

		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		try{
			list = homeworkTestDao.getTeaTeachClass(paramMap);
		}catch(Exception e){
			logger.error("查询某教师教的班级异常getTeaTeachClass", e);
			throw e;
		}
		return list;
	}

	/**
	 * @description 查询某教师教的课程对应的班级的作业列表
	 * @param  paramMap  Map<String,Object>
	 * @return List
	 * @throws Exception
	 */
	public Map<String,Object> getTeaHomeworkList(Map<String, Object> paramMap) throws Exception{

		Map<String, Object> resultMap = new HashMap<String,Object>();
		try{
			int pageNow = Integer.parseInt(paramMap.get("pageNow").toString());
			int pageSize = Integer.parseInt(paramMap.get("pageSize").toString());
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取列表信息
			List<Map<String, Object>> homeworkList = homeworkTestDao.getTeaHomeworkList(paramMap);
			if(homeworkList != null){
				for(Map<String, Object> map : homeworkList){
					map.put("taskType", 1);
					int homeworkNum = homeworkTestDao.getSubmitNum(map);
					map.put("homeworkNum", homeworkNum);
				}
			}
			resultMap.put("homeworkList", homeworkList);
			resultMap.put("pageNow", pageNow);
			//获取全部页数
			paramMap.put("pageNow", 0);
			paramMap.put("startNum", 0);
			List<Map<String, Object>> allList = homeworkTestDao.getTeaHomeworkList(paramMap);
			int totalPage = pageUtil.getTotalPage(allList, pageSize);
			resultMap.put("totalPage", totalPage);
		}catch(Exception e){
			logger.error("查询某教师教的课程对应的班级的作业列表异常getTeaHomeworkList", e);
			throw e;
		}
		return resultMap;
	}


	/**
	 * @description 查询某教师教的课程对应的班级的实验列表
	 * @param  paramMap  Map<String,Object>
	 * @return List
	 * @throws Exception
	 */
	public Map<String,Object> getTeaTestList(Map<String, Object> paramMap) throws Exception{

		Map<String, Object> resultMap = new HashMap<String,Object>();
		try{
			int pageNow = Integer.parseInt(paramMap.get("pageNow").toString());
			int pageSize = Integer.parseInt(paramMap.get("pageSize").toString());
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取列表信息
			List<Map<String, Object>> homeworkList = homeworkTestDao.getTeaTestList(paramMap);
			if(homeworkList != null){
				for(Map<String, Object> map : homeworkList){
					map.put("taskType", 2);
					int homeworkNum = homeworkTestDao.getSubmitNum(map);
					map.put("homeworkNum", homeworkNum);
				}
			}
			resultMap.put("testList", homeworkList);
			resultMap.put("pageNow", pageNow);
			//获取全部页数
			paramMap.put("pageNow", 0);
			paramMap.put("startNum", 0);
			List<Map<String, Object>> allList = homeworkTestDao.getTeaTestList(paramMap);
			int totalPage = pageUtil.getTotalPage(allList, pageSize);
			resultMap.put("totalPage", totalPage);
		}catch(Exception e){
			logger.error("查询某教师教的课程对应的班级的实验列表异常getTeaTestList", e);
			throw e;
		}
		return resultMap;
	}

	/**
	 * @description 查询某教师教的课程的某班级的作业详情情况（作业管理列表内页）
	 * @param  paramMap  Map<String,Object>
	 * @return List
	 * @throws Exception
	 */
	public Map<String,Object> getHomeWorkByClass(Map<String, Object> paramMap) throws Exception{

		Map<String, Object> resultMap = new HashMap<String,Object>();
		try{
			int pageNow = Integer.parseInt(paramMap.get("pageNow").toString());
			int pageSize = Integer.parseInt(paramMap.get("pageSize").toString());
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取列表信息
			List<Map<String, Object>> homeworkList = homeworkTestDao.getHomeWorkByClass(paramMap);
			resultMap.put("homeworkList", homeworkList);
			resultMap.put("pageNow", pageNow);
			//获取全部页数
			paramMap.put("pageNow", 0);
			paramMap.put("startNum", 0);
			List<Map<String, Object>> allList = homeworkTestDao.getHomeWorkByClass(paramMap);
			int totalPage = pageUtil.getTotalPage(allList, pageSize);
			resultMap.put("totalPage", totalPage);
			//查询成绩设置信息

		}catch(Exception e){
			logger.error("作业管理列表内页异常getHomeWorkByClass", e);
			throw e;
		}
		return resultMap;
	}

	/**
	 * @description 查询某教师教的课程的某班级的实验详情情况（实验管理列表内页）
	 * @param  paramMap  Map<String,Object>
	 * @return List
	 * @throws Exception
	 */
	public Map<String,Object> getTestByClass(Map<String, Object> paramMap) throws Exception{

		Map<String, Object> resultMap = new HashMap<String,Object>();
		try{
			int pageNow = Integer.parseInt(paramMap.get("pageNow").toString());
			int pageSize = Integer.parseInt(paramMap.get("pageSize").toString());
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取列表信息
			List<Map<String, Object>> homeworkList = homeworkTestDao.getTestByClass(paramMap);
			resultMap.put("testList", homeworkList);
			resultMap.put("pageNow", pageNow);
			//获取全部页数
			paramMap.put("pageNow", 0);
			paramMap.put("startNum", 0);
			List<Map<String, Object>> allList = homeworkTestDao.getTestByClass(paramMap);
			int totalPage = pageUtil.getTotalPage(allList, pageSize);
			resultMap.put("totalPage", totalPage);
		}catch(Exception e){
			logger.error("实验管理列表内页异常getTestByClass", e);
			throw e;
		}
		return resultMap;
	}

	/**作业管理评价学生作业
	 * @description 点击某个学生的作业评价学生作业ajax请求
	 * @param request
	 * @param response
	 * @param jsonStr  课程id，章节id，学生号，taskSoruce（总成绩）
	 * @return  课表信息
	 */
	public Map<String, Object> getHomeworkDetailBySId(Map<String, Object> paramMap,HttpServletRequest request) throws Exception{

		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<Map<String, Object>> answerList = new ArrayList<Map<String, Object>>();
		List<Integer> errList = new ArrayList<Integer>();
		Map<String,Object> newQuestion = new HashMap<String,Object>();
		ObjectMapper mapper = new ObjectMapper();
		try{
			//获取登录人id
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"stuorteaId"}, request, "userMsg");
			paramMap.put("checkId", sessionValues.get("stuorteaId"));
			//查看登录的老师有没有设置成绩的等级
			Map<String, Object> teacherMapUse = new HashMap<String, Object>();
			teacherMapUse.put("stuorteaId", sessionValues.get("stuorteaId"));
			teacherMapUse.put("courseId", paramMap.get("courseId"));
			Map<String, Object> levelValuesBefore = sourceDao.getProWedith(teacherMapUse);
			if(levelValuesBefore != null){
				//通过课程id和学号查询当前作业的试题
				Map<String,Object> homework = homeworkTestDao.getHomeworkDetailBySId(paramMap);
				String str = String.valueOf(homework.get("taskAddress"));
				String errstr = String.valueOf(homework.get("errlist"));
				if(str!=null&&!str.equals("")&&!str.equals("null")){
					//取出学生答案解析成对象后传给前台
					answerList = mapper.readValue(str, answerList.getClass());

				}if(errstr!=null&&!errstr.equals("")&&!errstr.equals("null")){
					//将错误题集合转换成对象传给前台
					errList = mapper.readValue(errstr, errList.getClass());
				}

				newQuestion.put("answerList", answerList);
				newQuestion.put("errList", errList);
				newQuestion.put("optionallsource", homework.get("optionallsource"));
				newQuestion.put("judgeallsource", homework.get("judgeallsource"));
				newQuestion.put("blankscount", homework.get("blankscount"));
				newQuestion.put("answersource", homework.get("answersource"));
				newQuestion.put("stuorteaId", homework.get("stuorteaId"));
				newQuestion.put("judworcount", homework.get("judworcount"));
				newQuestion.put("manyOpworcount", homework.get("manyOpworcount"));
				newQuestion.put("manyOptionallsource", homework.get("manyOptionallsource"));
				newQuestion.put("state", homework.get("state"));
				newQuestion.put("answercount", homework.get("answercount"));
				newQuestion.put("courseId", homework.get("courseId"));
				newQuestion.put("blanksallsource", homework.get("blanksallsource"));
				newQuestion.put("taskAddress", homework.get("taskAddress"));
				newQuestion.put("opworcount", homework.get("opworcount"));
				newQuestion.put("taskId", homework.get("taskId"));
				newQuestion.put("chapterName", homework.get("chapterName"));
				newQuestion.put("chapterId", homework.get("chapterId"));
				newQuestion.put("taskSoruce", homework.get("taskSoruce"));
				newQuestion.put("taskHtml", homework.get("taskHtml"));
				newQuestion.put("expreHtml", homework.get("expreHtml"));
				resultMap.put("homework", newQuestion);
				resultMap.put("result", true);
				resultMap.put("failMsg", "");
			}else{
				resultMap.put("result", false);
				resultMap.put("homework", null);
				resultMap.put("failMsg", "未设置成绩等级");
			}
			logger.info("点击某个学生的作业评价学生作业ajax请求参数为："+paramMap.toString());
		}catch(Exception e){
			logger.error("点击某个学生的作业评价学生作业ajax请求异常", e);
			throw e;
		}
		return resultMap;
	}



	/**
	 * @description 评价作业
	 * @param  paramMap  Map<String,Object>
	 * @return boolean true成功  false失败
	 * @throws Exception
	 */
	public Map<String, Object> assessHomework(Map<String, Object> paramMap,HttpServletRequest request) throws Exception{

		Map<String, Object> resultMap = new HashMap<String, Object>();
		try{
			/*Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
			if(String.valueOf(paramMap.get("taskSoruce"))!=null&&!String.valueOf(paramMap.get("taskSoruce")).equals("")){
				if(!pattern.matcher(String.valueOf(paramMap.get("taskSoruce"))).matches()){
					resultMap.put("result","fail");
					resultMap.put("failMsg","请输入正确分数");
					return resultMap;
				}
			}*/

			//获取登录人id
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"stuorteaId"}, request, "userMsg");
			paramMap.put("checkId", sessionValues.get("stuorteaId"));
			//查看登录的老师有没有设置成绩的等级
			Map<String, Object> teacherMapUse = new HashMap<String, Object>();
			teacherMapUse.put("stuorteaId", sessionValues.get("stuorteaId"));
			teacherMapUse.put("courseId", paramMap.get("courseId"));
//			Map<String, Object> levelValuesBefore = sourceDao.getProWedith(teacherMapUse);
			//代表作业标识
			paramMap.put("taskType", 1);
			//构建参数，不同类型参数不同
//			dataConcatFunc(paramMap, levelValuesBefore);
			paramMap.put("state",1);
			//查询这个学生这个课程所对应的平时分总分
			Map<String, Object> gradeMap = homeworkTestDao.getStuProfomaceGrade(paramMap);
			//保存该学生的平时分
			List<Map<String, Object>> relationList = homeworkTestDao.getStuReCourseExam(paramMap);
			//原来有就修改，没有就新增
			if(relationList != null && relationList.size() != 0){
				homeworkTestDao.saveStuReCourseExam(gradeMap);
			}else{
				//查询这个学生与这个课的关联关系
				//获取登录人与这个课的关门联标识
				Map<String, Object> relationMap = homeworkTestDao.getRelationMark(gradeMap);
				gradeMap.put("couSelectMark", relationMap.get("couSelectMark"));
				homeworkTestDao.addStuReCourseExam(gradeMap);
			}
			resultMap.put("result", true);
			//文件前缀路径
			String[] keysArray = {"server_address", "project_name","tomcatUrl"};
			Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
			String url = String.valueOf(urlmap.get("tomcatUrl"))+String.valueOf(urlmap.get("project_name"))+"upload/stuwork/";
			//判断文件夹是否存在，不存在则创建
			PubMethods.mkdirFile(url);
			String htmlStr = "";
			String htmlUrl = "";
			String wordUrl = "";
			//根据章节id查询章节名称
			paramMap.put("coursemark",1);
			Map<String,Object> chapterMap = chapterDao.getOneChapter(paramMap);
			String homeworkName = String.valueOf(paramMap.get("stuorteaId"))+"_"+String.valueOf(paramMap.get("courseId"))+"_"+String.valueOf(chapterMap.get("chapterName"))+"_"+"作业.doc";
			String homeworkNameHtml =  String.valueOf(paramMap.get("stuorteaId"))+"_"+String.valueOf(paramMap.get("courseId"))+"_"+String.valueOf(chapterMap.get("chapterName"))+"-"+"作业.html";
			//将前台传过来的html解码
			htmlStr = Escape.unescape(String.valueOf(paramMap.get("htmlStr")));
			htmlUrl = url+homeworkNameHtml;
			wordUrl = url+homeworkName;
			//将实验报告或者html转换成word文件
			PubMethods.coverHtml(htmlStr,String.valueOf(paramMap.get("cssStr")),wordUrl,htmlUrl);
			String returnUrl = String.valueOf(urlmap.get("server_address"))+String.valueOf(urlmap.get("project_name"))+"upload/stuwork/"+homeworkNameHtml;
			resultMap.put("url",returnUrl);
			resultMap.put("testfileName",homeworkNameHtml);
			paramMap.put("homefileName",homeworkNameHtml);
			paramMap.put("testfileName","");
			homeworkTestDao.assessHomeworkTest(paramMap);
			logger.info("评价作业参数为："+paramMap.toString());
		}catch(Exception e){
			resultMap.put("result", false);
			logger.error("评价作业异常", e);
			throw e;
		}
		return resultMap;
	}

	/**
	 * @description 评价实验
	 * @param  paramMap Map<String,Object>
	 * @return boolean true成功  false失败
	 * @throws Exception
	 */
	public Map<String, Object> assessTest(Map<String, Object> paramMap,HttpServletRequest request) throws Exception{

		Map<String, Object> resultMap = new HashMap<String, Object>();
		try{
			/*if(String.valueOf(paramMap.get("taskSoruce"))!=null&&!String.valueOf(paramMap.get("taskSoruce")).equals("")){
				Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
				if(!pattern.matcher(String.valueOf(paramMap.get("taskSoruce"))).matches()){
					resultMap.put("result",false);
					resultMap.put("failMsg","请输入正确分数");
					return resultMap;
				}
			}*/

			//获取登录人id
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"stuorteaId"}, request, "userMsg");
			paramMap.put("checkId", sessionValues.get("stuorteaId"));
			//查看登录的老师有没有设置成绩的等级
			Map<String, Object> teacherMapUse = new HashMap<String, Object>();
			teacherMapUse.put("stuorteaId", sessionValues.get("stuorteaId"));
			teacherMapUse.put("courseId", paramMap.get("courseId"));
			Map<String, Object> levelValuesBefore = sourceDao.getProWedith(teacherMapUse);
			if(levelValuesBefore==null){
				resultMap.put("result","fail");
				resultMap.put("failMsg","请设置成绩等级");
				return resultMap;
			}
			//代表实验标识
			paramMap.put("taskType", 2);
			//构建参数，不同类型参数不同
			dataConcatFunc(paramMap, levelValuesBefore);
			paramMap.put("state",1);
			//查询这个学生这个课程所对应的平时分总分
			Map<String, Object> gradeMap = homeworkTestDao.getStuProfomaceGrade(paramMap);
			//保存该学生的平时分
			List<Map<String, Object>> relationList = homeworkTestDao.getStuReCourseExam(paramMap);
			//原来有就修改，没有就新增
			//查询这个学生这个课程的关联标志
			List<Map<String, Object>> relationMapList = relationDao.getRelCourseTea(gradeMap);
			if(relationMapList != null && relationMapList.size() != 0){
				gradeMap.put("couSelectMark", relationMapList.get(0).get("couSelectMark"));
			}
			if(relationList != null && relationList.size() != 0){
				homeworkTestDao.saveStuReCourseExam(gradeMap);
			}else{
				homeworkTestDao.addStuReCourseExam(gradeMap);
			}
			resultMap.put("result", true);
			//文件前缀路径
			String[] keysArray = {"server_address", "project_name","tomcatUrl"};
			Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
			String url = String.valueOf(urlmap.get("tomcatUrl"))+String.valueOf(urlmap.get("project_name"))+"upload/stuwork/";
			//判断文件夹是否存在，不存在则创建
			PubMethods.mkdirFile(url);
			String htmlStr = String.valueOf(paramMap.get("htmlStr"));
			String htmlUrl = "";
			String wordUrl = "";
			//根据章节id查询章节名称
			paramMap.put("coursemark",1);
			Map<String,Object> chapterMap = chapterDao.getOneChapter(paramMap);
			String homeworkName = String.valueOf(paramMap.get("stuorteaId"))+"_"+String.valueOf(paramMap.get("courseId"))+"_"+String.valueOf(chapterMap.get("chapterName"))+"_"+"实验报告.doc";
			String homeworkNameHtml =  String.valueOf(paramMap.get("stuorteaId"))+"_"+String.valueOf(paramMap.get("courseId"))+"_"+String.valueOf(chapterMap.get("chapterName"))+"-"+"实验报告.html";
			htmlUrl = url+homeworkNameHtml;
			wordUrl = url+homeworkName;
			//将实验报告或者html转换成word文件
			PubMethods.coverHtml(htmlStr,String.valueOf(paramMap.get("cssStr")),wordUrl,htmlUrl);
			String returnUrl = String.valueOf(urlmap.get("server_address"))+String.valueOf(urlmap.get("project_name"))+"upload/stuwork/"+homeworkNameHtml;
			resultMap.put("url",returnUrl);
			resultMap.put("testfileName",homeworkNameHtml);
			paramMap.put("testfileName",homeworkNameHtml);
			paramMap.put("homefileName","");
			homeworkTestDao.assessHomeworkTest(paramMap);
			logger.info("评价实验参数为："+paramMap.toString());
		}catch(Exception e){
			resultMap.put("result", false);
			logger.error("评价实验异常assessTest", e);
			throw e;
		}
		return resultMap;
	}

	/**
	 * @description 评价学生实验之动态获取成绩等级
	 * @param  paramMap Map<String,Object>
	 * @return boolean true成功  false失败
	 * @throws Exception
	 */
	public Map<String, Object> getTestTaskFraction(Map<String, Object> paramMap,HttpServletRequest request) throws Exception{

		Map<String, Object> resultMap = new HashMap<String, Object>();
		try{
			//获取登录人id
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"stuorteaId"}, request, "userMsg");
			paramMap.put("checkId", sessionValues.get("stuorteaId"));
			//查看登录的老师有没有设置成绩的等级
			Map<String, Object> teacherMapUse = new HashMap<String, Object>();
			teacherMapUse.put("stuorteaId", sessionValues.get("stuorteaId"));
			teacherMapUse.put("courseId", paramMap.get("courseId"));
			Map<String, Object> levelValuesBefore = sourceDao.getProWedith(teacherMapUse);
			if(levelValuesBefore==null){
				paramMap.put("result","fail");
				paramMap.put("failMsg","请设置成绩等级");
				return paramMap;
			}
			paramMap.put("result","success");
			paramMap.put("failMsg","");
			//构建参数，不同类型参数不同
			dataConcatFunc(paramMap, levelValuesBefore);
			logger.info("评价实验参数为："+paramMap.toString());
		}catch(Exception e){
			logger.error("评价实验异常assessTest", e);
			throw e;
		}
		return paramMap;
	}

	/**
	 * @description 构建评价的参数
	 * @param paramMap 评价的表单参数
	 * @param levelValuesBefore 这个教师这个课程的所有成绩设置分数
	 * @description:当前实验评价的设置为100~90分为‘优’，80~89分为‘良’60~79分为‘中’0~59分为'差'，该设置可以在‘成绩设置’的‘评价设置’中更改
	 * */
	private void dataConcatFunc(Map<String, Object> paramMap, Map<String, Object> levelValuesBefore) throws Exception {
			//改成通过分数转换成等级(前台给我传转换成的等级)
			BigDecimal taskSoruce = new BigDecimal(String.valueOf(paramMap.get("taskSoruce")));
			if(taskSoruce.compareTo(new BigDecimal(String.valueOf(levelValuesBefore.get("excellent"))))==0||taskSoruce.compareTo(new BigDecimal(String.valueOf(levelValuesBefore.get("excellent"))))==1
				||taskSoruce.compareTo(new BigDecimal(String.valueOf(levelValuesBefore.get("good"))))==0||taskSoruce.compareTo(new BigDecimal(String.valueOf(levelValuesBefore.get("good"))))==1){
				//说明该分数大于或等于优的等级，则等级应该是优
				paramMap.put("taskFraction", "优");
			}if((taskSoruce.compareTo(new BigDecimal(String.valueOf(levelValuesBefore.get("inso"))))==0||taskSoruce.compareTo(new BigDecimal(String.valueOf(levelValuesBefore.get("inso"))))==1)
				&&taskSoruce.compareTo(new BigDecimal(String.valueOf(levelValuesBefore.get("good"))))==-1){
				//说明该分数大于或等于良的等级，则等级应该是良
				paramMap.put("taskFraction", "良");
			}if((taskSoruce.compareTo(new BigDecimal(String.valueOf(levelValuesBefore.get("bad"))))==0||taskSoruce.compareTo(new BigDecimal(String.valueOf(levelValuesBefore.get("bad"))))==1)
					&&taskSoruce.compareTo(new BigDecimal(String.valueOf(levelValuesBefore.get("inso"))))==-1){
				//说明该分数大于或等于中的等级，则等级应该是中
				paramMap.put("taskFraction", "中");
			}if(taskSoruce.compareTo(new BigDecimal(String.valueOf(levelValuesBefore.get("bad"))))==-1||taskSoruce.compareTo(new BigDecimal(0))==0){
				//说明该分数小于差的等级，则等级应该是差
				paramMap.put("taskFraction", "差");
			}
	}

	/**
	 * @description 添加作业或实验
	 * @param  paramMap Map<String,Object>
	 * @return boolean true成功  false失败
	 * @throws Exception
	 */
	public Map<String,Object>  addTask(Map<String, Object> paramMap, HttpServletRequest request) throws Exception{

		boolean result = false;
		String textjson = "";
		String errStr = "";
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//选择题错误个数
		int opworcount = 0;
		//多选选择题错误个数
		int manyOpworcount = 0;
		//判断题错误个数
		int judworcount = 0;
		//单选选择题总分数
		BigDecimal optionallsource = new BigDecimal(0);
		//多选选择题总分数
		BigDecimal manyOptionallsource = new BigDecimal(0);
		//判断题总分数
		BigDecimal judgeallsource = new BigDecimal(0);
		//错误题集合
		List<Integer> errList = new ArrayList<Integer>();
		//错误信息
		String msg = "";
		Map<String,Object> returnMap = new HashMap<>();
		try{
			logger.info("添加作业或实验,参数的大小为："+String.valueOf(paramMap.get("taskAddress")).length());
			//备注：20180827学生端应该下载自己答好的题
			//文件前缀路径
			String[] keysArray = {"server_address", "project_name","tomcatUrl"};
			Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
			String url = String.valueOf(urlmap.get("tomcatUrl"))+String.valueOf(urlmap.get("project_name"))+"upload/stuwork/";
			String stuUrl = String.valueOf(urlmap.get("server_address"))+String.valueOf(urlmap.get("project_name"))+"upload/stuwork/";
			//测试用的
//			 url = "C:\\Users\\Administrator\\Desktop\\xxbg\\";
			//判断文件夹是否存在，不存在则创建
			PubMethods.mkdirFile(url);
			String htmlStr = "";
			String htmlUrl = "";
			String wordUrl = "";
			//根据章节id查询章节名称
			paramMap.put("coursemark",1);
			Map<String,Object> chapterMap = chapterDao.getOneChapter(paramMap);
			String homeworkName = String.valueOf(paramMap.get("stuorteaId"))+"_"+String.valueOf(paramMap.get("courseId"))+"_"+String.valueOf(chapterMap.get("chapterName"))+"_"+"作业.doc";
			String homeworkNameHtml =  String.valueOf(paramMap.get("stuorteaId"))+"_"+String.valueOf(paramMap.get("courseId"))+"_"+String.valueOf(chapterMap.get("chapterName"))+"-"+"作业.html";
			//将前台传过来的html解码
			htmlStr = Escape.unescape(String.valueOf(paramMap.get("htmlStr")));
			htmlUrl = url+homeworkNameHtml;
			wordUrl = url+homeworkName;
			stuUrl = stuUrl+homeworkNameHtml;
			returnMap.put("stuUrl",stuUrl);
			if(String.valueOf(paramMap.get("taskAddress")).length()>20971520){
				returnMap.put("result",false);
				return returnMap;
			}
			//查询是否交过作业或实验，有标识
			List<Map<String, Object>> homeworkList = homeworkTestDao.selectMyHomework(paramMap);
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String submitTime = sdf.format(date);
			paramMap.put("submitTime", submitTime);
			paramMap.put("convertFile","");
			String filpathWord = "";
			paramMap.put("homefileName",homeworkNameHtml);
			//将实验报告或者html转换成word文件
			PubMethods.coverHtml(htmlStr,String.valueOf(paramMap.get("cssStr")),wordUrl,htmlUrl);
				if(Integer.parseInt(String.valueOf(paramMap.get("taskType")))==1){
					List<Map<String,Object>> list = (List<Map<String, Object>>) paramMap.get("mapList");
					if(list.size()!=0){
						textjson = mapper.writeValueAsString(list);
						paramMap.put("taskAddress", textjson);
						//将学生提交的答案进行比对自动将选择题计算分数
						//通过问题主键查询tasklibrary表查每道题的正确答案
						List<Map<String,Object>> questonList =  teaStatisticsDao.getAllTaskLibraryListById(list);
						//计算选择、判断错误个数和得分情况
						Map<String,Object> coutMap = this.coutMethod(questonList,list,paramMap);
						//将前台给的学生答案集合每个做空格、回车处理
						for(int j=0;j<list.size();j++){
							if(String.valueOf(list.get(j).get("ansquesContent"))!=null){
								String ansquesContent = String.valueOf(list.get(j).get("ansquesContent")).replaceAll("\n", "<br>");
								ansquesContent = String.valueOf(list.get(j).get("ansquesContent")).replaceAll("\r", "<br>");
								list.get(j).put("ansquesContent", ansquesContent);
							}
						}
						opworcount = Integer.valueOf(String.valueOf(coutMap.get("opworcount")));
						judworcount = Integer.valueOf(String.valueOf(coutMap.get("judworcount")));
						manyOpworcount = Integer.valueOf(String.valueOf(coutMap.get("manyOpworcount")));
						manyOptionallsource = (BigDecimal) coutMap.get("manyOptionallsource");
						optionallsource = (BigDecimal) coutMap.get("optionallsource");
						judgeallsource = (BigDecimal) coutMap.get("judgeallsource");
						//将后台自动算的分数放到总分数里taskSoruce
						BigDecimal taskSoruce = manyOptionallsource.add(optionallsource).add(judgeallsource);
						errList = (List<Integer>) coutMap.get("errList");
						paramMap.put("opworcount", opworcount);
						paramMap.put("judworcount", judworcount);
						paramMap.put("manyOpworcount", manyOpworcount);
						paramMap.put("optionallsource", optionallsource);
						paramMap.put("judgeallsource", judgeallsource);
						paramMap.put("manyOptionallsource", manyOptionallsource);
						paramMap.put("taskSoruce", taskSoruce);
						errStr = mapper.writeValueAsString(errList);
						paramMap.put("errList", errStr);

					/* 20180807yxj说不需要转成文件，所以不给我传htmlstr和cssstr
					//文件名
					filpathWord = String.valueOf(paramMap.get("stuorteaId"))+"_"+String.valueOf(courseDetail.get("courseName"))+"_"+String.valueOf(paramMap.get("chapterNum"))+"_"+"作业.doc";
					String filePath = path+filpathWord;
					//将html转换word文件
					PubMethods.coverHtml(String.valueOf(paramMap.get("htmlStr")),String.valueOf(paramMap.get("cssStr")),filePath);*/
					}else{
						//说明教师生成的试题是空卷
						paramMap.put("opworcount", 0);
						paramMap.put("judworcount", 0);
						paramMap.put("manyOpworcount", 0);
						paramMap.put("manyOptionallsource", 0);
						paramMap.put("optionallsource", 0);
						paramMap.put("judgeallsource", 0);
						paramMap.put("taskSoruce", 0);
						paramMap.put("taskAddress", errStr);
						paramMap.put("errList", errStr);
					}

					//将作业信息进行保存
					List<Map<String, Object>> historyList = homeworkTestDao.getStuHomeHistory(paramMap);
					paramMap.put("homeHtml",textjson);
					if(CollectionUtils.isEmpty(historyList)){
						//添加记录
						homeworkTestDao.addStuHomeHistory(paramMap);
					}else{
						//修改记录
						homeworkTestDao.saveStuHomeHistory(paramMap);
					}

				}if(Integer.parseInt(String.valueOf(paramMap.get("taskType")))==2){
					//说明提交的是实验报告，没有选择题不需要后台算
					paramMap.put("opworcount", 0);
					paramMap.put("judworcount", 0);
					paramMap.put("manyOpworcount", 0);
					paramMap.put("manyOptionallsource", 0);
					paramMap.put("optionallsource", 0);
					paramMap.put("judgeallsource", 0);
					paramMap.put("taskSoruce", 0);
					paramMap.put("errList", errStr);
					paramMap.put("taskAddress", paramMap.get("htmlStr"));
					/* 20180807yxj说不需要转成文件，所以不给我传htmlstr和cssstr
					filpathWord = String.valueOf(paramMap.get("stuorteaId"))+"_"+String.valueOf(courseDetail.get("courseName"))+"_"+String.valueOf(paramMap.get("chapterNum"))+"_"+"实验报告.doc";
					String filePath = path+filpathWord;
					//将html转换word文件
					PubMethods.coverHtml(String.valueOf(paramMap.get("htmlStr")),String.valueOf(paramMap.get("cssStr")),filePath);*/
				}
			//修改某个学生某课程某章节实验报告文件名
			paramMap.put("fileName",filpathWord);
			homeworkTestDao.updateFileTask(paramMap);
			//如果交过，就修改
			if(homeworkList != null && homeworkList.size() != 0){
				//修改某个学生某课程某章节作业或实验
				homeworkTestDao.saveTask(paramMap);
				//没交过，添加
			}else{
				//查询这个学生与这个课程的关联关系信息类型，存入作业表
				Map<String, Object> relationMap = homeworkTestDao.getRelationMark(paramMap);
				paramMap.put("couSelectMark", relationMap.get("couSelectMark"));
				homeworkTestDao.addTask(paramMap);
			}
			result = true;
			returnMap.put("result",result);
			logger.info("添加作业或实验,参数为："+paramMap.toString());
		}catch(Exception e){
			logger.error("添加作业或实验异常addTask", e);
			throw e;
		}
		return returnMap;
	}

	//计算选择、判断错误个数和得分情况
	private Map<String,Object> coutMethod(List<Map<String,Object>> questonList,List<Map<String,Object>> list,Map<String,Object> paramMap){
		//单选选择题错误个数
		int opworcount = 0;
		//多选选择题错误个数
		int manyOpworcount = 0;
		//判断题错误个数
		int judworcount = 0;
		//单选选择题总分数
		BigDecimal optionallsource = new BigDecimal(0);
		//多选选择题总分数
		BigDecimal manyOptionallsource = new BigDecimal(0);
		//判断题总分数
		BigDecimal judgeallsource = new BigDecimal(0);
		//错误题集合
		List<Integer> errList = new ArrayList<Integer>();
		//循环集合计算选择判断错误个数和得分
		for(int i=0;i<questonList.size();i++){
			for(int j=0;j<list.size();j++){
				if(Integer.parseInt(String.valueOf(questonList.get(i).get("tasklibrary_type")))==1||Integer.parseInt(String.valueOf(questonList.get(i).get("tasklibrary_type")))==2||Integer.parseInt(String.valueOf(questonList.get(i).get("tasklibrary_type")))==5){
					if(String.valueOf(list.get(j).get("questionId")).equals(String.valueOf(questonList.get(i).get("tasklibrary_id")))){
						//判断学生答案是否正确---单选
						if(String.valueOf(list.get(j).get("ansquesContent")).trim().toUpperCase().equals(String.valueOf(questonList.get(i).get("tasklibrary_answer")).trim().toUpperCase())&&(Integer)(questonList.get(i).get("tasklibrary_type"))==1){
							BigDecimal optionSource = new BigDecimal(String.valueOf(list.get(j).get("questionSource")));
							optionallsource = optionallsource.add(optionSource);
						}if(!(String.valueOf(list.get(j).get("ansquesContent")).trim().toUpperCase().equals(String.valueOf(questonList.get(i).get("tasklibrary_answer")).trim().toUpperCase()))&&(Integer)(questonList.get(i).get("tasklibrary_type"))==1){
							opworcount = opworcount+1;
							//将错误题主键加入到集合中
							int id = Integer.valueOf(String.valueOf(list.get(j).get("questionId")));
							errList.add(id);
						}
						//多选--判断是否答案正确 true不正确 false正确
						if(Integer.parseInt(String.valueOf(questonList.get(i).get("tasklibrary_type")))==5){
							boolean manyFlag = PubMethods.isManyOptionTure(String.valueOf(list.get(j).get("ansquesContent")).trim().toUpperCase(),String.valueOf(questonList.get(i).get("tasklibrary_answer")).trim().toUpperCase());
							if(!manyFlag){
								BigDecimal optionSource = new BigDecimal(String.valueOf(list.get(j).get("questionSource")));
								manyOptionallsource = manyOptionallsource.add(optionSource);
							}if(manyFlag){
								manyOpworcount = manyOpworcount+1;
								//将错误题主键加入到集合中
								int id = Integer.valueOf(String.valueOf(list.get(j).get("questionId")));
								errList.add(id);
							}
						}
						//判断学生答案是否正确---判断
						if(String.valueOf(list.get(j).get("ansquesContent")).trim().toUpperCase().equals(String.valueOf(questonList.get(i).get("tasklibrary_answer")).trim().toUpperCase())&&(Integer)(questonList.get(i).get("tasklibrary_type"))==2){
							BigDecimal judgeSource = new BigDecimal(String.valueOf(list.get(j).get("questionSource")));
							judgeallsource = judgeallsource.add(judgeSource);
						}if(!(String.valueOf(list.get(j).get("ansquesContent")).trim().toUpperCase().equals(String.valueOf(questonList.get(i).get("tasklibrary_answer")).trim().toUpperCase()))&&(Integer)(questonList.get(i).get("tasklibrary_type"))==2){
							judworcount = judworcount+1;
							//将错误题主键加入到集合中
							int id = Integer.valueOf(String.valueOf(list.get(j).get("questionId")));
							errList.add(id);
						}
					}
				}
			}
		}
		paramMap.put("errList", errList);
		paramMap.put("optionallsource", optionallsource);
		paramMap.put("opworcount", opworcount);
		paramMap.put("manyOptionallsource", manyOptionallsource);
		paramMap.put("manyOpworcount", manyOpworcount);
		paramMap.put("judgeallsource", judgeallsource);
		paramMap.put("judworcount", judworcount);
		return paramMap;
	}

	/**
	 * @description 添加某学生某课程的平时分
	 * @param  paramMap  Map<String,Object>
	 * @return boolean true成功  false失败
	 * @throws Exception
	 */
	public boolean addNormalNum(Map<String, Object> paramMap) throws Exception{
		boolean result = false;
		try{
			//获取总共的分数信息
			Map<String, Object> myDegreeMap = homeworkTestDao.getMyDegreeByCourse(paramMap);

			if(myDegreeMap == null){
				paramMap.put("preforSource", 0);
			}else{
				paramMap.put("preforSource", myDegreeMap.get("preforSource"));
			}
			//获取我是不是有信息
			Map<String, Object> myNormalGrade = homeworkTestDao.getMyNormalDegreeMessage(paramMap);
			if(myNormalGrade != null && myNormalGrade.get("stuorteaId") != null){
				homeworkTestDao.saveMyNormalDegree(paramMap);
			}else{
				homeworkTestDao.addMyNormalDegree(paramMap);
			}
			result = true;
			logger.info("添加某学生某课程的平时分,参数为："+paramMap.toString());
		}catch(Exception e){
			logger.error("添加某学生某课程的平时分异常addNormalNum", e);
			throw e;
		}
		return result;
	}

	/**
	 * @description 给商莹封的评价作业和试验的时候，重新计算分数的方法，
	 * @param
	 * @param
	 * @param
	 * @return
	 * @throws Exception
	 */
	public boolean reCountDegree(Map<String, Object> paramMap,HttpSession session, HttpServletRequest request) throws Exception{
		boolean result = false;
		try{
			//查询当前要评价学生所在班级所属课程(参数是学号、课程号)
			Map<String,Object> stuClaCouMap = relStuClassDao.getStuClaAndCou(paramMap);//这个结果里有班号
			//查询当前班级当前课程相关学生的平时成绩(参数是班号、课程号)
			List<Map<String,Object>> stuList = sourceDao.getStuSourceList(stuClaCouMap);
			for(Map<String,Object> map : stuList){
				//平时成绩换算值(参数是班号、课程号、学生平时分)
				BigDecimal finPromaceSource = sourceActionImpl.proSource(stuClaCouMap, map,session,request);
				//将这个学生，这个课的平时成绩换算值放入数据库
				map.put("actMark", 1);
				map.put("finPromaceSource", finPromaceSource);
				map.put("courseId", paramMap.get("courseId"));
				//将这个学生，这个课的平时成绩换算值放入数据库
				questionDao.saveQuestionByStuId(map);
				//考试成绩换算值（参数考试成绩）
				BigDecimal examSource = sourceActionImpl.examSource(stuClaCouMap, map,session,request);
				//学生最后的成绩
				BigDecimal finSumSource = finPromaceSource.add(examSource);
				//将和此评价学生所在同一所班级的学生总成绩重新计算后更改数据库(参数是班号、课程号)
				stuClaCouMap.put("sumSource", finSumSource);
				stuClaCouMap.put("stuorteaId", map.get("stuorteaId"));
				sourceDao.updateSorceBySId(stuClaCouMap);
			}
			result = true;
			logger.info("修改等级的重新计算分数方法，参数为："+paramMap.toString());
		}catch(Exception e){
			logger.error("重新计算分数的方法异常reCountDegree", e);
			throw e;
		}
		return result;
	}


	/**
	 * @description 辅助方法 通过优良中差获取字段对应值信息
	 * @param args1 优良中差文字数组
	 * @param  args2 数据库对应字段名数组
	 * @param  paramMap 数据库获取的参数数据
	 * @return Map<String, Object> key为优良中差输入的值，value为数据库对应这个字段的值
	 * @throws Exception
	 */
	public Map<String, Object> getLevelMark(String[] args1, String[] args2, Map<String, Object> paramMap) throws Exception{

		Map<String, Object> resultMap = new HashMap<String, Object>();
		try{
			for(int i = 0; i < args1.length; i++){
				resultMap.put(String.valueOf(paramMap.get(args2[i])), args1[i]);
			}
		}catch(Exception e){
			logger.error("通过优良中差获取字段对应值信息方法异常getLevelMark", e);
			throw e;
		}
		return resultMap;
	}

	/**3.0
	 * @description 保存学生实验笔记信息
	 * @param paramMap 学号，课程号，第几章节num，html笔记信息str字符串
	 * @return Map<String, Object> 
	 * @throws Exception
	 */
	public Map<String, Object> saveNote(Map<String, Object> paramMap, HttpServletRequest request) throws Exception{

		Map<String, Object> resultMap = new HashMap<String, Object>();
		try{
			//获取登录人id
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"stuorteaId"}, request, "userMsg");
			paramMap.put("stuorteaId", sessionValues.get("stuorteaId"));
			//查询这个学生，这个课，这个章节交没交过实验笔记，交过就保存，没交过就添加
			Map<String, Object> noteMsg = homeworkTestDao.getStuNoteByCouAndCptNum(paramMap);
			if(noteMsg == null || noteMsg.get("stuorteaId") == null){
				homeworkTestDao.addNote(paramMap);
			}else{
				homeworkTestDao.saveNote(paramMap);
			}
			resultMap.put("result", true);
			logger.info("保存学生实验笔记,参数为："+paramMap.toString());
		}catch(Exception e){
			logger.error("保存学生实验笔记异常saveNote", e);
			throw e;
		}
		return resultMap;
	}

	/**3.0
	 * @description 查询某个学生，某个课，某个章节数的试验笔记信息
	 * @param paramMap 学号，课程号，第几章节num
	 * @return Map<String, Object> 
	 * @throws Exception
	 */
	public Map<String, Object> getNoteById(Map<String, Object> paramMap) throws Exception{

		Map<String, Object> resultMap = new HashMap<String, Object>();
		try{
			//获取实验笔记信息
			resultMap = homeworkTestDao.getNoteById(paramMap);
		}catch(Exception e){
			logger.error("查询某个学生，某个课，某个章节数的试验笔记信息异常getNoteById", e);
			throw e;
		}
		return resultMap;
	}

	/**
	 * @description 查询这个课这个章节，这个学生是不是交过作业或实验，如果交过，直接返回失败信息
	 * @param req,
	 * @param courseId，
	 * @param  chapterNum 第几章节num，
	 * @param   taskType 类型
	 * @return Map<String, Object>
	 */
	public boolean uploadWordMark(HttpServletRequest req,long courseId, long chapterNum, long taskType){
		SessionValues session = new SessionValues();
		try {
			//构建参数
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"stuorteaId"}, req, "userMsg");
			sessionValues.put("courseId", courseId);
			sessionValues.put("chapterNum", chapterNum);
			sessionValues.put("taskType", taskType);
			//查询
			List<Map<String, Object>> workList = homeworkTestDao.selectMyHomework(sessionValues);
			return uploadWordMark(workList, "taskFraction");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("工具方法异常uploadWordMark", e);
			return true;
		}
	}

	/**
	 * @description 查询某个list是不是为空，或list(0)的指定字段是不是为空
	 * @param list  List<Map<String,Object>>
	 * @param   key String
	 * @return Map<String, Object>
	 */
	public boolean uploadWordMark(List<Map<String,Object>> list, String key){
		if(list == null || list.size() == 0){
			return false;
		}else{
			if(list.get(0).get(key) == null || list.get(0).get(key).toString().equals("")){
				return false;
			}
		}
		return true;
	}

	/**xzx
	 * @description 教师修改某个课程对应的优良中差对应分数的时候，将task与exam进行修改的方法
	 @param paramMap stuorteaId教师id，courseId课程id，excellent 优的分值，good良的分值，inso中的分值，bad差的分值
	  * */
	public boolean saveTaskAndExamPerformaceDegree(Map<String, Object> paramMap, HttpSession session,HttpServletRequest request){
		//修改task中的评分值
		boolean resultTask = saveTaskDegreeByArr(paramMap, new String[] {"taskSoruce","taskFraction"}, new String[] {"优","良","中","差"}, new String[] {"excellent","good","inso","bad"});
		//获取这个教师教的所有学生的task中的分数总分
		List<Map<String, Object>> taskDegreeList = null;
		try {
			//获取每个学生这个课程的平时分数总分(未结课的)
			taskDegreeList = homeworkTestDao.getMyStuTaskSumDegree(paramMap);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		//将exam中的平时分数进行修改
		Boolean resultExam = saveExamPerforList(paramMap, taskDegreeList);
		//将exam中平时分数换算值进行修改
		saveFinActSource(paramMap, session,request);
		//修改exam总分数值
		if(!saveTotalCount(paramMap, session,request)){
			return false;
		}
		return true;
	}

	/**
	 * @description 修改优良中差的时候修改对应的exam中的平时分数换算值
	 * */
	public boolean saveFinActSource(Map<String, Object> paramMap, HttpSession session, HttpServletRequest request){
		boolean result = false;
		//重新计算这个教师教的这个课程的所有学生的有成绩的总分数,courseId,stuorteaId
		List<Map<String, Object>> degreeList = null;
		try {
			degreeList = sourceDao.getMyStuDegreeByCouId(paramMap);
			Map<String, Object> map;
			for (int i = 0; i < degreeList.size(); i++) {
				map = new HashMap<String, Object>();
				map.put("stuorteaId",degreeList.get(i).get("stuorteaId"));
				map.put("courseId",paramMap.get("courseId"));
				map.put("actMark", 1);
				//平时分数换算值
				map.put("finPromaceSource",getMySumDegree(map, degreeList.get(i), session,request).get("actDegree"));
				//将这个学生，这个课的平时成绩换算值放入数据库
				questionDao.saveQuestionByStuId(map);
			}
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * @description 批量修改exam中的平时分数
	 * @param
	 * */
	public boolean saveExamPerforList(Map<String, Object> paramMap, List<Map<String, Object>> degreeList){
		for(int i = 0; i < degreeList.size(); i++){
			degreeList.get(i).put("courseId",paramMap.get("courseId"));
			try {
				sourceDao.updateMyStuPerformaceDegree(degreeList.get(i));
				logger.info("批量修改exam中的平时分数，参数为："+paramMap.toString()+" 分数集合为："+degreeList.toString());
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("批量修改exam中的平时分数异常saveExamPerforList", e);
				return false;
			}
		}
		return true;
	}

	/**
	 * @description 重新计算这个教师教的这个课程的有分数的总分
	 *
	 * */
	public boolean saveTotalCount(Map<String, Object> paramMap, HttpSession session,HttpServletRequest request){
		try {
			//重新计算这个教师教的这个课程的所有学生的有成绩的总分数,courseId,stuorteaId
			List<Map<String, Object>> degreeList = sourceDao.getMyStuDegreeByCouId(paramMap);
			Map<String, Object> map;
			for (int i = 0; i < degreeList.size(); i++) {
				map = new HashMap<String, Object>();
				map.put("stuorteaId",degreeList.get(i).get("stuorteaId"));
				map.put("courseId",paramMap.get("courseId"));
				//获取这个学生的总分数
				degreeList.get(i).put("sumSource", getMySumDegree(map, degreeList.get(i), session,request).get("sumDegree"));
				degreeList.get(i).put("courseId", paramMap.get("courseId"));
			}
			//批量修改这些学生的exam总分数据
			boolean resultSum = saveExamSumDegree(degreeList);
			logger.info("重新计算这个教师教的这个课程的学生总分,参数为："+paramMap.toString());
		}catch(Exception e){
			logger.error("重新计算这个教师教的这个课程的学生总分异常saveTotalCount", e);
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * @description  批量修改这些学生的exam总分数据
	 * @param
	 * */
	public boolean saveExamSumDegree(List<Map<String, Object>> degreeList){
		for(int i = 0; i < degreeList.size(); i++){
			try {
				sourceDao.saveExamSumDegreeUtil(degreeList.get(i));
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}

	/**
	 * @description 获取某个学生的总分信息
	 * @param paramMap :学生学号 ， 课程号。
	 * @param degreeListI 学生的学号以及这个课的exam得分
	 * @param session
	 * */
	public Map<String, Object> getMySumDegree(Map<String, Object> paramMap, Map<String, Object> degreeListI, HttpSession session,HttpServletRequest request){
		Map<String, Object> mapReturn = new HashMap<String, Object>();
		try{
			//查询当前要评价学生所在班级所属课程(参数是学号、课程号)
			Map<String, Object> stuClaCouMap = relStuClassDao.getStuClaAndCou(paramMap);//这个结果里有班号
			//平时成绩换算值(参数是班号、课程号、学生平时分)
			BigDecimal finPromaceSource = sourceActionImpl.proSource(stuClaCouMap, degreeListI, session,request);
			//考试成绩换算值（参数考试成绩）
			BigDecimal examSource = new BigDecimal(0);
			examSource = sourceActionImpl.examSource(stuClaCouMap, degreeListI, session,request);
			//学生最后的成绩
			BigDecimal finSumSource = finPromaceSource.add(examSource);
			mapReturn.put("sumDegree", finSumSource);
			mapReturn.put("actDegree", finPromaceSource);
			return mapReturn;
		}catch(Exception e){
			logger.error("获取某个学生的总分信息异常getMySumDegree",e);
			e.printStackTrace();
		}
		return mapReturn;
	}

	/**
	 * @description 将map数据中的值赋值到map转换成list的方法
	 * @param paramMap 需要的信息值
	 * @param wordsList 需要生成list中的map的key
	 * */
	public List<Map<String, Object>> getListUtil(Map<String, Object> paramMap,String[] keys, String[] wordsList, String[] columnList){
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map;
		for(int i = 0; i < wordsList.length; i++){
			map = new HashMap<String, Object>();
			map.put(keys[0],wordsList[i]);
			map.put(keys[1], paramMap.get(columnList[i]));
			list.add(map);
		}
		return list;
	}

	/**
	 * @description 根据优良中差进行数据库更新操作
	 *@param paramMap  courseId  stuorteaId教师id
	 * @param keys 要存入sql方法的参数key
	 * @param levelWords 等级的文字数组（优良中差）
	 * @param columnList 对应优良中差的数据库字段名
	 * */
	public boolean saveTaskDegreeByArr(Map<String, Object> paramMap, String[] keys, String[] levelWords, String[] columnList){
		for(int i = 0; i < levelWords.length; i++){
			paramMap.put(keys[0], paramMap.get(columnList[i]));
			paramMap.put(keys[1], levelWords[i]);
			try {
				homeworkTestDao.saveTaskLevelChange(paramMap);
			} catch (Exception e) {
				logger.error("根据优良中差进行数据库更新操作异常saveTaskDegreeByArr", e);
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}

	/**@description 通过学号课程号第几章节得到学生的实验信息
	 *
	 * */
	public void getMyTestDetail(String jsonStr, HttpServletResponse response,HttpServletRequest request){
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		try{
			map = mapper.readValue(jsonStr, map.getClass());
			//获取登录人id
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"stuorteaId"}, request, "userMsg");
			paramMap.put("checkId", sessionValues.get("stuorteaId"));
			//查看登录的老师有没有设置成绩的等级
			Map<String, Object> teacherMapUse = new HashMap<String, Object>();
			teacherMapUse.put("stuorteaId", sessionValues.get("stuorteaId"));
			teacherMapUse.put("courseId", map.get("courseId"));
			Map<String, Object> levelValuesBefore = sourceDao.getProWedith(teacherMapUse);
			if(levelValuesBefore==null){
				map.put("result","fail");
				map.put("failMsg","请设置成绩等级");
				courseActionImpl.responseStream(response, mapper.writeValueAsString(map));
			}
			//动态获取提示信息：当前实验评价的设置为100~90分为‘优’，80~89分为‘良’60~79分为‘中’0~59分为'差'，该设置可以在‘成绩设置’的‘评价设置’中更改。
			String tipsStr = "当前实验评价的设置为"+new BigDecimal(String.valueOf(levelValuesBefore.get("excellent")))+"~"
					+new BigDecimal(String.valueOf(levelValuesBefore.get("good")))+"分为‘优’，"+new BigDecimal(String.valueOf(levelValuesBefore.get("inso")))+
					"~"+new BigDecimal(String.valueOf(levelValuesBefore.get("good"))).subtract(new BigDecimal(1))+"分为‘良’，"+
					new BigDecimal(String.valueOf(levelValuesBefore.get("bad")))+"~"+new BigDecimal(String.valueOf(levelValuesBefore.get("inso"))).subtract(new BigDecimal(1))+"分为‘中’，"+
					0+"~"+new BigDecimal(String.valueOf(levelValuesBefore.get("bad"))).subtract(new BigDecimal(1))+"分为‘差’，该设置可以在‘成绩设置’的‘评价设置’中更改。";

			map.put("taskType",2);
			map = homeworkTestDao.getMyTestDetail(map);
			if(map == null){
				map = new HashMap<String, Object>();
				map.put("result", "success");
//				map.put("actualSumSource",map.get("actualTestSumSource"));
				map.put("actualSumSource",levelValuesBefore.get("excellent"));
				courseActionImpl.responseStream(response, mapper.writeValueAsString(map));
			}else{
				map.put("result", "success");
				if(map.get("taskFraction")!=null){
					//说明评价完了，可以给下载地址了
					String[] keysArray = {"tomcatUrl", "project_name","server_address"};
					Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
					String testfileName = String.valueOf(map.get("testfileName"));
					String url = String.valueOf(urlmap.get("server_address"))+String.valueOf(urlmap.get("project_name"))+"upload/stuwork/"+testfileName;
					map.put("url",url);
				}
				map.put("tipsStr",tipsStr);
				map.put("souceMark",levelValuesBefore.get("souceMark"));
				map.put("actualSumSource",levelValuesBefore.get("excellent"));
				courseActionImpl.responseStream(response, mapper.writeValueAsString(map));
			}
		}catch(Exception e){
			e.printStackTrace();
			map.put("result", "fail");
			map.put("failMsg","获取失败");
		}
	}

	/**@description 通过学号课程号第几章节得到学生的实验信息
	 *
	 * */
	public void getMyHomeworkDetail(String jsonStr, HttpServletResponse response,HttpServletRequest request){
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		List<Map<String, Object>> answerList = new ArrayList<Map<String, Object>>();
		try{
			map = mapper.readValue(jsonStr, map.getClass());
			//获取登录人id
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"stuorteaId"}, request, "userMsg");
			paramMap.put("checkId", sessionValues.get("stuorteaId"));
			//查看登录的老师有没有设置成绩的等级
			Map<String, Object> teacherMapUse = new HashMap<String, Object>();
			teacherMapUse.put("stuorteaId", sessionValues.get("stuorteaId"));
			teacherMapUse.put("courseId", map.get("courseId"));
			Map<String, Object> levelValuesBefore = sourceDao.getProWedith(teacherMapUse);
			if(levelValuesBefore==null){
				map.put("result","fail");
				map.put("failMsg","请设置成绩等级");
				courseActionImpl.responseStream(response, mapper.writeValueAsString(map));
			}
			//动态获取提示信息：当前实验评价的设置为100~90分为‘优’，80~89分为‘良’60~79分为‘中’0~59分为'差'，该设置可以在‘成绩设置’的‘评价设置’中更改。
			String tipsStr = "当前实验评价的设置为"+new BigDecimal(String.valueOf(levelValuesBefore.get("excellent")))+"~"
					+new BigDecimal(String.valueOf(levelValuesBefore.get("good")))+"分为‘优’，"+new BigDecimal(String.valueOf(levelValuesBefore.get("inso")))+
					"~"+new BigDecimal(String.valueOf(levelValuesBefore.get("good"))).subtract(new BigDecimal(1))+"分为‘良’，"+
					new BigDecimal(String.valueOf(levelValuesBefore.get("bad")))+"~"+new BigDecimal(String.valueOf(levelValuesBefore.get("inso"))).subtract(new BigDecimal(1))+"分为‘中’，"+
					0+"~"+new BigDecimal(String.valueOf(levelValuesBefore.get("bad"))).subtract(new BigDecimal(1))+"分为‘差’，该设置可以在‘成绩设置’的‘评价设置’中更改。";


			map.put("taskType",1);
			map = homeworkTestDao.getMyTestDetail(map);
			if(map == null){
				map = new HashMap<String, Object>();
				map.put("result", "success");
				courseActionImpl.responseStream(response, mapper.writeValueAsString(map));
			}else{
				map.put("result", "success");
				String str = String.valueOf(map.get("taskAddress"));
				if(str!=null&&!str.equals("")&&!str.equals("null")){
					//取出学生答案解析成对象后传给前台
					answerList = mapper.readValue(str, answerList.getClass());
				}
				map.put("answerList",answerList);
				if(map.get("taskFraction")!=null){
					//说明评价完了，可以给下载地址了
					String[] keysArray = {"tomcatUrl", "project_name","server_address"};
					Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
					String homefileName = String.valueOf(map.get("homeworkNameHtml"));
					map.put("homefileName",homefileName);
					String url = String.valueOf(urlmap.get("server_address"))+String.valueOf(urlmap.get("project_name"))+"upload/stuwork/"+homefileName;
					map.put("url",url);
				}
				map.put("tipsStr",tipsStr);
				map.put("souceMark",levelValuesBefore.get("souceMark"));
				courseActionImpl.responseStream(response, mapper.writeValueAsString(map));
			}
		}catch(Exception e){
			e.printStackTrace();
			map.put("result", "fail");
			map.put("failMsg","获取失败");
		}
	}

	/**@description 通过课程id班级id获取他们之间的结课标志
	 *@param map classId courseId
	 * */
	public Map<String, Object> getClassCourseEndMark(Map<String, Object> map) {
		try {
			List<Map<String, Object>> list = relationDao.getRelCourseClass(map);
			if(list != null && list.size() != 0){
				map.put("classEndMark", list.get(0).get("classEndMark"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * @description 查询某学生交的实验报告信息，或作业信息
	 * @param courseId chapterNum taskType stuorteaId
	 * */
	public Map<String, Object> getStuTask(Map<String, Object> paramMap){

		try{
			List<Map<String, Object>> list = homeworkTestDao.selectMyHomework(paramMap);
			if(list != null && list.size() != 0){
				return list.get(0);
			}else{
				return null;
			}
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * @description 保存学生的实验信息
	 * @param courseId chapterNum taskType stuorteaId
	 * */
	public void saveStuTestPractice(String jsonStr, HttpServletResponse res, HttpServletRequest req) {
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> map = new HashMap<String, Object>();
		try{
			map = mapper.readValue(jsonStr, map.getClass());
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"stuorteaId"}, req, "userMsg");
			map.put("stuorteaId", sessionValues.get("stuorteaId"));
			logger.info("保存学生的实验信息,参数的大小为："+String.valueOf(map.get("taskAddress")).length());
			if(String.valueOf(map.get("taskAddress")).length()>20971520){
				map.put("result","fail");
				map.put("failMsg", "实验报告内容长度超限，请精简内容");
				courseActionImpl.responseStream(res, mapper.writeValueAsString(map));
			}
			//查询是否有数据
			List<Map<String, Object>> list = homeworkTestDao.getStuTestHistory(map);
			map.put("taskType",2);
			map.put("expreHtml",map.get("taskAddress"));
			if(CollectionUtils.isEmpty(list)){
				//添加记录
				homeworkTestDao.addStuTestHistory(map);
			}else{
				//修改记录
				homeworkTestDao.saveStuTestHistory(map);
			}
			map.put("result","success");
			courseActionImpl.responseStream(res, mapper.writeValueAsString(map));
		}catch(Exception e){
			e.printStackTrace();
			map.put("result","fail");
			try {
				courseActionImpl.responseStream(res, mapper.writeValueAsString(map));
			} catch (JsonProcessingException e1) {
				e1.printStackTrace();
			}
		}
	}

	/**
	 * @description 保存学生的作业信息
	 * @param courseId chapterNum taskType stuorteaId
	 * */
	public void saveStuHomePractice(String jsonStr, HttpServletResponse res, HttpServletRequest req) {
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> map = new HashMap<String, Object>();
		try{
			map = mapper.readValue(jsonStr, map.getClass());
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"stuorteaId"}, req, "userMsg");
			map.put("stuorteaId", sessionValues.get("stuorteaId"));
			logger.info("保存学生的作业信息,参数的大小为："+String.valueOf(map.get("taskAddress")).length());
			if(String.valueOf(map.get("taskAddress")).length()>20971520){
				map.put("result","fail");
				map.put("failMsg", "作业内容长度超限，请精简内容");
				courseActionImpl.responseStream(res, mapper.writeValueAsString(map));
			}
			//查询是否有数据
			List<Map<String, Object>> list = homeworkTestDao.getStuHomeHistory(map);
			List<Map<String,Object>> mapList = (List<Map<String, Object>>) map.get("mapList");
			String textjson = "";
			if(mapList.size()!=0){
				textjson = mapper.writeValueAsString(mapList);
			}

			map.put("homeHtml",textjson);
			if(CollectionUtils.isEmpty(list)){
				//添加记录
				homeworkTestDao.addStuHomeHistory(map);
			}else{
				//修改记录
				homeworkTestDao.saveStuHomeHistory(map);
			}
			map.put("result","success");
			courseActionImpl.responseStream(res, mapper.writeValueAsString(map));
		}catch(Exception e){
			e.printStackTrace();
			map.put("result","fail");
			try {
				courseActionImpl.responseStream(res, mapper.writeValueAsString(map));
			} catch (JsonProcessingException e1) {
				e1.printStackTrace();
			}
		}
	}


	/**
	 * @description 保存学生的实验信息
	 * @param courseId chapterNum taskType stuorteaId
	 * */
	public boolean saveStuTestPracticeUse(Map<String, Object> map) {
		try{
			if(Integer.parseInt(String.valueOf(map.get("taskType")))==2){
				//说明保存的是实验报告
				map.put("expreHtml",map.get("taskAddress"));
			}
			//查询是否有数据
			List<Map<String, Object>> list = homeworkTestDao.getStuTestHistory(map);
			//通过章节id查询章节信息
			map.put("coursemark",1);
			Map<String, Object> chapterMap = chapterDao.getOneChapter(map);
			if(CollectionUtils.isEmpty(list)){
				//添加记录
				map.put("expreHtml",chapterMap.get("expreHtml"));
				homeworkTestDao.addStuTestHistory(map);
			}else{
				//修改记录
				homeworkTestDao.saveStuTestHistory(map);
			}
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * @description 查询某个学生某课程某章节保存的实验信息
	 * */
	public Map<String, Object> getStuTestHistory(Map<String, Object> map){
		try {
			//查询是否有数据
			List<Map<String, Object>> list = homeworkTestDao.getStuTestHistory(map);
			if (!CollectionUtils.isEmpty(list)) {
				return list.get(0);
			}else{
				return null;
			}
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * @description 查询某个学生某课程某章节保存的作业信息
	 * */
	public Map<String, Object> getStuHomeHistory(Map<String, Object> map){
		try {
			//查询是否有数据
			List<Map<String, Object>> list = homeworkTestDao.getStuHomeHistory(map);
			if (!CollectionUtils.isEmpty(list)) {
				return list.get(0);
			}else{
				return null;
			}
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}


	/**
	 * @description 下载课程的每个类型课件的方法，
	 * @param jsonStr ={"courseId":课程id，"stuorteaId":"0005","downloadType":下载类型：1作业，2实验报告，3试卷}
	 * @param req
	 * @param res
	 * @return map中get：result,true成功，false失败
	 *         如果是失败的，从map中get出errorMsg，是失败信息。
	 */
	public void downloadCourseWorkFile(String jsonStr, HttpServletRequest req, HttpServletResponse res)  {
		//获取参数
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		try {
			paramMap = mapper.readValue(jsonStr, paramMap.getClass());
			//获取当前登录人id
			String teaId = PubMethods.loginId(req);
			paramMap.put("teaId",teaId);
			//通过课程id及要查询的类型的参数将所有文档以及他们文件的前缀拼接好弄出来得到一个String[] file 数组（里面都是文件的全路径）
			//获取文件前缀
			Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", new String[] {"server_address", "project_name","tomcatUrl"});
			String url = "";
			String downUrl = "";
			if(Integer.parseInt(String.valueOf(paramMap.get("downloadType")))==3){
				paramMap.put("mark",2);//标识是下载试卷
				url = (String)urlmap.get("tomcatUrl")+(String)urlmap.get("project_name")+"upload/stuExam/";
				downUrl = (String)urlmap.get("server_address")+(String)urlmap.get("project_name")+"upload/stuExam/";
			}else{
				paramMap.put("mark",1);
				url = (String)urlmap.get("tomcatUrl")+(String)urlmap.get("project_name")+"upload/stuwork/";
				downUrl = (String)urlmap.get("server_address")+(String)urlmap.get("project_name")+"upload/stuwork/";
			}
			//测试用的
			/*url = "C:\\Users\\Administrator\\Desktop\\xxbg\\aaa\\";
			downUrl = "C:\\Users\\Administrator\\Desktop\\xxbg\\aaa\\";*/
			//获取所有文件
			List<Map<String,Object>> fileList = this.getCourseWorkFileByType(paramMap, url);
			logger.info("批量下载课件信息，得到的文件集合为："+ fileList);
			//获取当前学生所属的所有课程（并且是当前登录人所教授的）
			List<Map<String,Object>> courseList = homeworkTestDao.getCourseListBySIdOrTeaId(paramMap);
			if(fileList != null && fileList.size() != 0 && courseList!=null && courseList.size()!=0){
				Map<String,Object> returnMap = FileDownloadZipUtil.downloadWorkZipUtil(url+"download" , fileList, req, res,courseList,paramMap);
				//年月日
				String fileName = String.valueOf(returnMap.get("fileName"));
				courseActionImpl.responseStream(res,"{\"result\":\"success\",\"url\":\""+downUrl+"download"+"/"+teaId+"/"+fileName+"\",\"failMsg\":\"\"}");
			}else{
				courseActionImpl.responseStream(res,"{\"result\":\"error\",\"failMsg\":\"暂无信息\"}");
			}
			logger.info("下载课程课件信息，参数为："+jsonStr);
		}catch(FileNotFoundException fe){
			fe.printStackTrace();
			logger.error("下载文件操作，找不到文件错误.", fe);
			courseActionImpl.responseStream(res,"{\"result\":\"error\",\"failMsg\":\"文件无法获取，下载失败\"}");
		}
		catch (Exception e) {
			e.printStackTrace();
			logger.error("下载课程课件信息异常downloadCourseFileFunc", e);
			courseActionImpl.responseStream(res,"{\"result\":\"error\",\"failMsg\":\"下载错误\"}");
		}
	}
	/**
	 * @description 通过课程id及要查询的类型的参数将所有文档以及他们文件的前缀拼接好弄出来得到一个String[] file 数组（里面都是文件的全路径）
	 * @param paramMap  jsonStr ={"courseId":课程id，"stuorteaId":"0005","downloadType":下载类型：1作业，2实验报告，3试卷}
	 * @param path 所有文件前缀  eg:d:/123/
	 * @return String[] fileArr 保存的是所有文件的全路径
	 */
	public List<Map<String,Object>>  getCourseWorkFileByType(Map<String, Object> paramMap, String path) throws Exception {
		paramMap.put("path", path);
		//通过课程id及类型从数据库中查询出来所有这个类型的文件信息集合，并将文件前缀作为参数放入进行拼接
		List<Map<String,Object>> fileList =  homeworkTestDao.getCourseWorkFileByType(paramMap);
		return fileList;
	}



}